package com.manager.system.service.impl;


import com.manager.common.dao.SuperDao;
import com.manager.common.utils.DataTools;
import com.manager.common.utils.ObjectUtils;
import com.manager.common.vo.PageVO;
import com.manager.model.System_Setting;
import com.manager.system.service.SystemSettingService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Transactional
public class SystemSettingServiceImpl extends SuperDao<Object> implements SystemSettingService {


    @Override
    public PageVO getPageMap(System_Setting model) {
        String sql = " from  System_Setting t where 1 = 1 ";
        Map<String,Object> map = new HashMap<>();
        List<Object> params = new ArrayList<>();

        if(StringUtils.isNotEmpty(model.getSystemName())){
            sql += " and t.systemName like # ";
            params.add("%"+model.getSystemName()+"%");
        }


        sql = ObjectUtils.replaceIndexByList(sql,params);

        List<System_Setting> list = this.getList(sql, params.toArray(), model.getStart(), model.getLimit(), "");
        int sum = this.getListCount("select count(*) " + sql, params.toArray(), "");
        int count = (int)Math.ceil(Double.valueOf(sum)/Double.valueOf(model.getLimit()));

        return PageVO.create(model.getStart(),count,list);
    }

    @Override
    public void addModel(System_Setting model) throws Exception {
        String sql = " select count(*) from  System_Setting t where t.systemKey = ?1 ";
        int count  = this.getListCount(sql,new Object[]{model.getSystemKey()});
        if(count > 0){
            throw new Exception("唯一标识不能相同!");
        }
        this.addT(model);
    }

    @Override
    public void updateModel(System_Setting model) throws Exception {
        String sql = " select count(*) from  System_Setting t where t.systemKey = ?1 and t.id != ?2 ";
        int count  = this.getListCount(sql,new Object[]{model.getSystemKey(),model.getId()});
        if(count > 0){
            throw new Exception("唯一标识不能相同!");
        }
        System_Setting systemSetting = this.getT(System_Setting.class,model.getId());
        BeanUtils.copyProperties(model,systemSetting,new String[]{"id"});
        this.updateT(systemSetting);
    }

    @Override
    public void deleteModel(System_Setting model) {
        System_Setting systemSetting = this.getT(System_Setting.class,model.getId());
        this.delete(systemSetting);
    }

    @Override
    public void initSystemSettingCache() {
        String sql = " from  System_Setting t where 1 = 1 ";
        List<System_Setting> list = this.getList(sql,0,0,"");
        list.forEach( v -> {
            DataTools.systemSettingMap.put(v.getSystemKey(),v);
        });
    }
}
